import { ConfigProvider, Tag } from 'antd';
import React, { useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import { addTab, setActiveTab, removeTab } from '@/store/slices/tabsSlice';
import { searchRoute } from '@/utils/util.js';
import { routerArr } from '@/router/index.jsx';
import './index.scss';

const LayoutTabs = React.memo(() => {
  const { tabList, activeTab } = useSelector(state => state.tabs);
  const dispatch = useDispatch();
  const { pathname } = useLocation();
  const navigate = useNavigate();

  useEffect(() => {
    if (pathname !== '/') {
      const route = searchRoute(pathname, routerArr)
      dispatch(addTab({
        key: route.path,
        label: route.meta?.title
      }))
    }
  }, [pathname])

  // 新增：监听activeTab变化，自动跳转
  useEffect(() => {
    if (activeTab !== pathname) {
      navigate(activeTab)
    }
  }, [activeTab, pathname, navigate])

  const handleTabChange = (key) => {
    dispatch(setActiveTab(key))
    navigate(key)
  }

  const onCloseTab = (targetKey, e) => {
    e.stopPropagation()
    if (tabList.length === 1 || tabList[0].key === targetKey) {
      return ;
    }
    dispatch(removeTab(targetKey))
  }

  return (
    <div className='layout-tabs'>
      <ConfigProvider>
        {tabList.map((tab, idx) => (
          <Tag
            key={tab.key}
            closable={idx !== 0}
            color={tab.key === activeTab ? 'processing' : 'default'}
            onClick={() => handleTabChange(tab.key)}
            onClose={e => {
              if (idx !== 0) onCloseTab(tab.key, e)
            }}
          >
            {tab.key === activeTab && <i className={'ant-tag-icon'}></i>}
            {tab.label}
          </Tag>
        ))}
      </ConfigProvider>
    </div>
  )
})

export default LayoutTabs
